package com.miyake.server;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.miyake.client.datamanage.Table;
import com.miyake.server.dsaccess.NodeManager;

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class DsTable {
	@PrimaryKey 
	@Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)  
	private Key key;
	
	@Persistent
	private String nodeKey;

	public Key getKey() {
		return key;
	}

	public void setKey(Key key) {
		this.key = key;
	}


	public String getNodeKey() {
		return nodeKey;
	}

	public void setNodeKey(String nodeKey) {
		this.nodeKey = nodeKey;
	}

	public String getEncodedKey() {
		return KeyFactory.keyToString(key);
	}
	
	public Table toRemoteObject() {
		String key = NodeManager.getInstance().getNode(nodeKey).getParentKey();
		DsData data = NodeManager.getInstance().getData(key);
		Table table = new Table();
		table.setKey(getEncodedKey());
		
		String[] rowdata = new String[data.getColumnCount()];
		int col = 0;
		for (String title : data.getTitles()) {
			rowdata[col++] = title;
		}
		table.addRowData(rowdata);
		for (int row = 0; row < data.getDataString(0).length; row++) {
			rowdata = new String[data.getColumnCount()];
			for (col = 0; col < data.getColumnCount(); col++) {
				rowdata[col] = data.getDataString(col)[row];
//				table.addData(data.getDataString(i));
			}
			table.addRowData(rowdata);
		}
		return table;
	}

}
